package com.ssm.juc.thread1;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
//import lombok.extern.slf4j.Slf4j;

import java.util.List;

//@Slf4j
public class ThreadLocalTest {

    /**
     * 未初始化的本地线程变量
     */
    private static ThreadLocal<User> userThreadLocal = new ThreadLocal<>();


    public static void main(String[] args) throws InterruptedException {

        int threadNum = 100;
        List<Thread> threadList = Lists.newArrayList();

        for (int i = 0; i < threadNum; ++i) {
            long userId = i;
            Thread t = new Thread(() -> {
                User value = new User(userId, "lanxing" + userId, "2x");
                try {
                    // 设置变量值

                    userThreadLocal.set(value);
                    // 使用变量
                    doSomething();
                } finally {
                    // 移除变量
                    //userThreadLocal.remove();   //移除ThreadLocal变量
                }
            }, "T" + i);
            threadList.add(t);
            t.start();
        }

        for (int i = 0; i < threadNum; ++i) {
            threadList.get(i).join();
        }
    }

    private static void doSomething() {
        System.out.println("Use ThreadLocal variable :" + JSON.toJSONString(userThreadLocal.get()));
    }
}

class User {
    private Long id;
    private String name;
    private String level;
    private byte[] bytes;

    public User(Long id, String name, String level) {
        this.id = id;
        this.name = name;
        this.level = level;
        this.bytes = new byte[128];
    }
}